package ru.ng.sample.ui.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.ng.sample.core.notes.Note;
import ru.ng.sample.core.notes.NoteManager;
import ru.ng.sample.ui.validators.NoteValidator;

/**
 * User: ngorosh
 * Date: 18.05.11
 * Time: 21:44
 */
@Controller
@RequestMapping( "/notes" )
public class NotesController
{
    @Autowired
    private NoteManager noteManager;

    @RequestMapping( method = RequestMethod.GET )
    public void notes( ModelMap modelMap )
    {
        modelMap.addAttribute( "notes", noteManager.getNotes() );
    }

    @RequestMapping( "/edit/{noteId}" )
    public String editNote( @PathVariable int noteId, ModelMap map )
    {
        Note note = noteManager.getNote( noteId );
        map.put( "note", note );
        return "editNote";
    }

    @RequestMapping( value = {"/edit/save", "/save"}, method = RequestMethod.POST )
    public String editSubmit( @ModelAttribute Note note, BindingResult result )
    {
        new NoteValidator().validate( note, result );
        if ( result.hasErrors() )
        {
            return "editNote";
        }
        else
        {
            saveNote( note );
            return "redirect:/notes";
        }
    }

    private Note saveNote(Note note)
    {
        if (note == null)
            throw new NullPointerException( "note is null!!!" );

        if (note.getId() == null)
        {
            return noteManager.add( note );
        }
        else
        {
            return noteManager.edit( note );
        }
    }

    @RequestMapping( value = "/delete/{noteId}" )
    public String delete( @PathVariable int noteId )
    {
        noteManager.delete( noteId );
        return "redirect:/notes";
    }

    @RequestMapping( value = "/add" )
    public String add( ModelMap map )
    {
        map.put( "note", new Note() );
        return "editNote";
    }
}
